import { defineStore } from 'pinia'
import { Ref, ref } from 'vue'
import { useUserStore } from '@/store'

// 编辑状态常量
export const EDIT_STATUS = {
  EDITING: 'editing', // 申请编辑
  RELEASE: 'release', // 释放编辑
  LOCKED: 'locked', // 被锁定（其他人正在编辑）
  DENIED: 'denied' // 申请被拒绝
} as const

export interface EditRequestInfo {
  status: 'pending' | 'success' | 'denied'
  resolve: (value: CUSTOMAPI.EditReturnModel) => void
}
//当前筛选项
export const taskFilter: Ref<string> = ref('all')
export const useEditStore = defineStore('edit', () => {
  const userStore = useUserStore()

  // 存储单元格编辑状态 cellId -> EditInfoModel
  const editingCells = ref(new Map<string, CUSTOMAPI.EditInfoModel>())
  // 存储行编辑状态 rowId -> EditInfoModel
  const editingRows = ref(new Map<string, CUSTOMAPI.EditInfoModel>())
  // 存储编辑请求状态 cellId -> EditRequestInfo
  const editRequests = ref(new Map<string, EditRequestInfo>())

  /**
   * 申请编辑权限
   * @param cellId 单元格ID
   * @returns Promise<CUSTOMAPI.EditReturnModel> 完整的服务器返回结果
   */
  const requestEditPermission = (cellId: string) => {
    return new Promise<CUSTOMAPI.EditReturnModel>((resolve) => {
      editRequests.value.set(cellId, {
        status: 'pending',
        resolve
      })
    })
  }

  /**
   * 处理服务器返回的编辑权限响应
   * @param editReturn 服务器返回的完整结果
   */
  const handleEditResponse = (editReturn: CUSTOMAPI.EditReturnModel) => {
    const cellId = editReturn.editInfo.cellId
    const request = editRequests.value.get(cellId)
    const isRow = cellId.split('-').length === 2 // 判断是否为行编辑（只有一个'-'）

    switch (editReturn.result) {
      case EDIT_STATUS.EDITING:
        // 获取编辑权成功
        if (request) {
          if (isRow) {
            editingRows.value.set(cellId, editReturn.editInfo)
          } else {
            editingCells.value.set(cellId, editReturn.editInfo)
          }
          request.resolve(editReturn)
          editRequests.value.delete(cellId)
        }
        break

      case EDIT_STATUS.LOCKED:
        // 单元格或行被其他人锁定
        if (isRow) {
          editingRows.value.set(cellId, editReturn.editInfo)
          console.log(editingRows.value)
        } else {
          editingCells.value.set(cellId, editReturn.editInfo)
        }
        if (request) {
          request.resolve(editReturn)
          editRequests.value.delete(cellId)
        }
        break

      case EDIT_STATUS.DENIED:
        // 申请被拒绝
        if (request) {
          request.resolve(editReturn)
          editRequests.value.delete(cellId)
        }
        break

      case EDIT_STATUS.RELEASE:
        // 释放编辑状态
        if (isRow) {
          editingRows.value.delete(cellId)
          console.log('释放行', editingRows.value)
        } else {
          editingCells.value.delete(cellId)
        }
        break

      default:
        break
    }
  }
  const handleInitResponse = (initEditStatus: Record<string, CUSTOMAPI.SimpleUserModel>) => {
    // 使用 Object.entries 来遍历普通对象
    for (const [cellId, user] of Object.entries(initEditStatus)) {
      const isRow = cellId.split('-').length === 2 // 判断是否为行编辑（只有一个'-'）

      if (isRow) {
        editingRows.value.set(cellId, {
          cellId,
          editorInfo: user,
          status: EDIT_STATUS.EDITING
        })
      } else {
        editingCells.value.set(cellId, {
          cellId,
          editorInfo: user,
          status: EDIT_STATUS.EDITING
        })
      }
    }
    console.log('editingRows', editingRows.value)
    console.log('editingCells', editingCells.value)
  }
  /**
   * 释放编辑权限
   * @param cellId 单元格ID
   */
  const releaseEditPermission = (cellId: string) => {
    editingCells.value.delete(cellId)
  }

  /**
   * 清理用户的所有编辑状态
   * @param userId 用户ID
   */
  const clearUserEditing = (userId: number) => {
    // 清理单元格编辑状态
    for (const [cellId, editInfo] of editingCells.value.entries()) {
      if (editInfo.editorInfo.id === userId) {
        editingCells.value.delete(cellId)
      }
    }
    // 清理行编辑状态
    for (const [rowId, editInfo] of editingRows.value.entries()) {
      if (editInfo.editorInfo.id === userId) {
        editingRows.value.delete(rowId)
      }
    }
  }

  /**
   * 获取单元格的编辑状态
   * @param cellId 单元格ID
   * @returns EditInfoModel | undefined
   */
  const getCellEditInfo = (cellId: string) => {
    return editingCells.value.get(cellId)
  }

  /**
   * 检查单元格是否可编辑
   * @param cellId 单元格ID
   * @returns
   *  - true: 可以编辑
   *  - {editing: true, editor: EditInfoModel}: 当前被他人编辑
   */
  const checkCellEditable = (cellId: string) => {
    const currentEditor = editingCells.value.get(cellId)

    if (!currentEditor) {
      return true
    }

    // 如果当前用户就是编辑者，也返回 true
    if (currentEditor.editorInfo.id === userStore.user.id) {
      return true
    }

    return {
      editing: true,
      editor: currentEditor
    }
  }

  return {
    editingCells,
    editingRows,
    editRequests,
    requestEditPermission,
    handleEditResponse,
    releaseEditPermission,
    handleInitResponse,
    clearUserEditing,
    getCellEditInfo,
    EDIT_STATUS,
    taskFilter,
    checkCellEditable
  }
})
